package org.jaaksi.kottlindemo.util

import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent

/**
 * Android 监听软键盘弹出与收起
 * @param decorView 这个view要是全屏的view，如果Fragment不是全屏的，就传Activity的decorView
 */
class SoftInputHelper(
    private var decorView: View,
    private val listener: (shown: Boolean) -> Unit
) :
    LifecycleObserver {
    private var onGlobalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null

    // 软键盘是否显示
    var isShowing = false
        private set

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private fun onResume() {
        addKeyBoardShowListener()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private fun onStop() {
        removeKeyBoardShowListener()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun onDestroy() {
        removeKeyBoardShowListener()
    }

    fun addKeyBoardShowListener() {
        removeKeyBoardShowListener()
        onGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
            val rect = Rect()
            // 获取根View的可见范围
            decorView.getWindowVisibleDisplayFrame(rect)
//            if (rect.bottom < screenHeight * 4 / 5) {
            if (rect.bottom < decorView.height * 4 / 5) { // 键盘显示
                if (!isShowing) {
                    isShowing = true
                    listener.invoke(true)
                }
            } else {
                if (isShowing) {
                    isShowing = false
                    listener.invoke(false)
                }
            }
        }

        decorView.viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)
    }

    fun removeKeyBoardShowListener() {
        decorView.viewTreeObserver.removeOnGlobalLayoutListener(onGlobalLayoutListener)
//        onGlobalLayoutListener = null
    }
}